package com.hhd.pdf.component;

import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.exceptions.PdfException;
import com.itextpdf.text.Element;
import org.dom4j.tree.DefaultText;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PdfComponentDelegate {
    @Autowired
    @Lazy
    List<PdfComponent> pdfComponents;

    @Autowired
    @Lazy
    TextComponent textComponent;

    public List<Element> genElements(GeneratorContext context) {
        String name = getParseingElementName(context);
        for (PdfComponent pdfComponent : pdfComponents) {
            if (name.equals(pdfComponent.getName())) {
                return pdfComponent.genElements(context);
            }
        }
        throw new PdfException("不支持的组件: " + name);
    }

    private static String getParseingElementName(GeneratorContext context) {
        GeneratorContext.RuntimeData runtimeData = context.getRuntimeData();
        org.dom4j.Element parsingElement = runtimeData.getParsingElement();
        return parsingElement.getName();
    }

    public List<Element> genElementText(DefaultText node, GeneratorContext context) {
        return textComponent.genElements(node, context);
    }
}
